﻿using UnityEngine;

public class VibratorImp{

    private AndroidJavaObject VibratorInstance = null;

    private static VibratorImp vibratorImp;

    public static VibratorImp Instance {
        get {
            if (vibratorImp == null) {
                vibratorImp = new VibratorImp();
#if UNITY_ANDROID
                using (AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
                {
                    using (AndroidJavaObject activityContext = activityClass.GetStatic<AndroidJavaObject>("currentActivity"))
                    {
                        using (AndroidJavaClass pluginClass = new AndroidJavaClass("tool.foldcc.unitytools.Vibrator"))
                        {
                            if (pluginClass != null)
                            {
                                vibratorImp.VibratorInstance = new AndroidJavaObject("tool.foldcc.unitytools.Vibrator");
                                vibratorImp.VibratorInstance.Call<bool>("Init", activityContext);
                            }
                        }
                    }
                }
#endif
                if (vibratorImp.VibratorInstance == null)
                {
                    Debug.LogError("Init vibrator service err"); 
                }
            }
            return vibratorImp;
        }
    }

    /// <summary>
    /// 启动震动
    /// </summary>
    /// <param name="ms">震动时间(毫秒)</param>
    public void StartVibrator(int ms) {
        VibratorInstance.Call("StartVibrator", ms);
    }

    /// <summary>
    /// 启动高级震动 可自行控制震动间隔来间接控制震动强度
    /// </summary>
    /// <param name="msArray">数组下标从0开始第一个为震动时长第二个为停顿时长以此循环</param>
    /// <param name="repeat">从指定下标开始 -1表示从头开始 默认为-1</param>
    public void LoopStartVibrator(long[] msArray , int repeat = -1) {
        VibratorInstance.Call("LoopStartVibrator", msArray , repeat);
    }

    /// <summary>
    /// 停止震动
    /// </summary>
    public void StopVibrator() {
        VibratorInstance.Call("StopVibrator");
    }

}
